import java.awt.Color;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

/**
 * Klasse Controller
 * 
 * @author GUI-Programmer
 * @version 19.10.2011
 */
public class Controller implements AdjustmentListener,
								   MouseListener,
								   ComponentListener,
								   MouseMotionListener,
								   ActionListener,       
								   WindowListener,
								   HyperlinkListener    {
	// Attribut
	private View view;
	
	
	// Konstruktor
	public Controller(View view) {
		this.view = view;
	}

	// Methoden
	@Override
	public void adjustmentValueChanged(AdjustmentEvent evt) {
		Object src = evt.getSource();
		if(src.equals(view.scrlpnSubject.getVerticalScrollBar())) {
			view.scrlpnFrom.getVerticalScrollBar().setValue(evt.getValue());
		}
		if(src.equals(view.scrlpnFrom.getVerticalScrollBar())) {
			view.scrlpnSubject.getVerticalScrollBar().setValue(evt.getValue());
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent evt) {
		Object src = evt.getSource();
		for(int i=0; i<view.lblFrom1.size(); i++) {
			if(src.equals(view.lblFrom1.get(i)) || src.equals(view.lblSubject1.get(i))) {
				if(evt.getButton() == MouseEvent.BUTTON1) {
					view.btnLoeschen.setName(""+i);
					view.readMail(view.lblFrom1.get(i).getText(), view.lblSubject1.get(i).getText(), (i+1));
				}
				if(evt.getButton() == MouseEvent.BUTTON3) {
					if(src.equals(view.lblFrom1.get(i))) {
						view.lblFrom1.get(i).add(view.popupmenuMails);
						view.popupmenuMails.show(view.lblFrom1.get(i), evt.getX(), evt.getY());
						view.popupmenuMails.setName(""+i);
					}
					if(src.equals(view.lblSubject1.get(i))) {
						view.lblSubject1.get(i).add(view.popupmenuMails);
						view.popupmenuMails.show(view.lblSubject1.get(i), evt.getX(), evt.getY());
						view.popupmenuMails.setName(""+i);
					}
				}
			}
		}
		for(int i=0; i<view.lblAtachments1.size(); i++) {
			JLabel label = view.lblAtachments1.get(i);
			if(src.equals(label)) {
				try {
					if(i==0 || (i>0 && i != (view.lblAtachments1.size()-1))) {
						new AttachementHandler(view, "download one", label.getText(), i);
					}
				}
				catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		if(src.equals(view.lblAlle)) {
			new AttachementHandler(view, "download all", null, -1);
		}
	}
	
	@Override
	public void mouseExited(MouseEvent evt) {
		Object src = evt.getSource();
		for(int i=0; i<view.lblFrom1.size(); i++) {
			if(view.lblFrom1.get(i) != null && view.lblSubject1.get(i) != null) {
				if(src.equals(view.lblFrom1.get(i)) || src.equals(view.lblSubject1.get(i))) {
					view.lblFrom1.get(i).setFont(view.fontListPlain);
					view.lblSubject1.get(i).setFont(view.fontListPlain);
					view.lblFrom1.get(i).setForeground(view.colorLabelsWhite);
					view.lblSubject1.get(i).setForeground(view.colorLabelsWhite);
				}
			}
		}
	}
	
	@Override
	public void mouseEntered(MouseEvent evt) { }
	
	@Override
	public void mousePressed(MouseEvent evt) {
		Object src = evt.getSource();
		if(src.equals(view.btnAktualisieren)) {
			if(view.btnAktualisieren.mouseIsInArc(evt.getX(), evt.getY())) {
				view.aktualisiereMails();
			}
		}
		if(src.equals(view.btnEMailVerfassen)) {
			if(view.btnEMailVerfassen.mouseIsInArc(evt.getX(), evt.getY())) {
				view.pnlAnhang2.removeAll();
				view.filelist.removeAll(view.filelist);
				view.pnlSouth.setVisible(false);
				view.cl_pnlCenter.show(view.pnlCenter, "2");
				view.thisFrame.setTitle("Google Mail Desktop Application - Email verfassen");
				view.txtfldAdresse.requestFocus();
			}
		}
		if(src.equals(view.btnSenden)) {
			if(view.btnSenden.mouseIsInArc(evt.getX(), evt.getY())) {
				view.progressCircle2.start();
				
				SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

					@Override
					protected Void doInBackground() throws Exception {
						String address = view.txtfldAdresse.getText();
						String subject = view.txtfldBetreff1.getText();
						String mailText = view.edtrpnEMailText1.getText();
						try {
							view.mailtool.sendMail(address, subject, mailText, view.filelist);
							view.lblFehler.setText(view.nachrichtVersand);
							view.lblFehler.setForeground(Color.GREEN);
							view.nachricht = true;
						} catch(Exception ex) {
							view.lblFehler.setText(view.nachrichtFehler);
							view.lblFehler.setForeground(Color.RED);
							view.nachricht = true;
						}
						return null;
					}
					
					protected void done() {
						view.pnlSouth.setVisible(true);
						view.progressCircle2.stop();
						view.cl_pnlCenter.show(view.pnlCenter, "1");
						view.txtfldAdresse.setText("");
						view.txtfldBetreff1.setText("");
						view.edtrpnEMailText1.setText("");
						view.thisFrame.setTitle("Google Mail Desktop Application - Posteingang");
					}
				};
				worker.execute();
			}
		}
		if(src.equals(view.btnAbbrechen)) {
			if(view.btnAbbrechen.mouseIsInArc(evt.getX(), evt.getY())) {
				view.pnlSouth.setVisible(true);
				view.cl_pnlCenter.show(view.pnlCenter, "1");
				view.txtfldAdresse.setText("");
				view.txtfldBetreff1.setText("");
				view.edtrpnEMailText1.setText("");
				view.thisFrame.setTitle("Google Mail Desktop Application - Posteingang");
			}
		}
		if(src.equals(view.btnZurueck)) {
			if(view.btnZurueck.mouseIsInArc(evt.getX(), evt.getY())) {
				view.pnlSouth.setVisible(true);
				view.cl_pnlCenter.show(view.pnlCenter, "1");
				view.progressCircle1.stop();
				view.txtfldVon.setText("");
				view.txtfldBetreff2.setText("");
				view.edtrpnEMailText2.setText("");
				view.thisFrame.setTitle("Google Mail Desktop Application - Posteingang");
			}
		}
		if(src.equals(view.btnLoeschen)) {
			if(view.btnLoeschen.mouseIsInArc(evt.getX(), evt.getY())) {
				int i = Integer.parseInt(view.btnLoeschen.getName());
				view.deleteMail(i);
				view.lblFehler.setText(view.nachrichtGeloescht);
				view.lblFehler.setForeground(Color.GREEN);
				view.nachricht = true;
				view.pnlSouth.setVisible(true);
				view.cl_pnlCenter.show(view.pnlCenter, "1");
				view.progressCircle1.stop();
				view.txtfldVon.setText("");
				view.txtfldBetreff2.setText("");
				view.edtrpnEMailText2.setText("");
				view.thisFrame.setTitle("Google Mail Desktop Application - Posteingang");
			}
		}
		if(src.equals(view.btnAntworten)) {
			if(view.btnAntworten.mouseIsInArc(evt.getX(), evt.getY())) {
				view.filelist.removeAll(view.filelist);
				view.pnlAnhang2.removeAll();
				view.cl_pnlCenter.show(view.pnlCenter, "2");
				view.progressCircle1.stop();
				view.txtfldAdresse.setText(view.txtfldVon.getText());
				view.txtfldVon.setText("");
				view.txtfldBetreff2.setText("");
				String neuerText = "ORIGINAL NACHRICHT VON: "+view.txtfldAdresse.getText()+"\n"
								  +"*************************************************************************\n"
								  +view.edtrpnEMailText2.getText()+"\n"
								  +"*************************************************************************\n\n";
				view.edtrpnEMailText1.setText(neuerText);
				view.edtrpnEMailText2.setText("");
				view.thisFrame.setTitle("Google Mail Desktop Application - Email verfassen");
				view.txtfldBetreff1.requestFocus();
			}
		}
	}
	
	@Override
	public void mouseReleased(MouseEvent evt) { }
	
	@Override
	public void mouseDragged(MouseEvent ect) { }

	@Override
	public void mouseMoved(MouseEvent evt) {
		Object src = evt.getSource();
		for(int i=0; i<view.lblFrom1.size(); i++) {
			if(src.equals(view.lblFrom1.get(i)) || src.equals(view.lblSubject1.get(i))) {
				view.lblFrom1.get(i).setFont(view.fontListBold);
				view.lblSubject1.get(i).setFont(view.fontListBold);
				view.lblFrom1.get(i).setForeground(view.colorLabelsBlue);
				view.lblSubject1.get(i).setForeground(view.colorLabelsBlue);
			}
		}
	}
	
	@Override
	public void componentHidden(ComponentEvent evt) { }
	
	@Override
	public void componentMoved(ComponentEvent evt) { }
	
	@Override
	public void componentResized(ComponentEvent evt) { }
	
	@Override
	public void componentShown(ComponentEvent evt) {
		Object src = evt.getSource();
		if(src.equals(view.pnlAlleEmails)) {
			if(view.nachricht) {
				view.newUpdate++;
				view.showInformation();
				view.nachricht = false;
			}
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent evt) {
		Object src = evt.getSource();
		if(src.equals(view.menuitemEmail)) {
			view.filelist.removeAll(view.filelist);
			view.pnlAnhang2.removeAll();
			int i = Integer.parseInt(view.popupmenuMails.getName());
			view.txtfldAdresse.setText(view.lblFrom1.get(i).getText());
			view.pnlSouth.setVisible(false);
			view.cl_pnlCenter.show(view.pnlCenter, "2");
			view.thisFrame.setTitle("Google Mail Desktop Application - Email verfassen");
			view.txtfldBetreff1.requestFocus();
		}
		if(src.equals(view.menuitemLesen)) {
			int i = Integer.parseInt(view.popupmenuMails.getName());
			view.btnLoeschen.setName(""+i);
			view.readMail(view.lblFrom1.get(i).getText(), view.lblSubject1.get(i).getText(), (i+1));
		}
		if(src.equals(view.menuitemLoeschen)) {
			SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
				@Override
				protected Void doInBackground() throws Exception {
					int i = Integer.parseInt(view.popupmenuMails.getName());
					view.deleteMail(i);
					view.lblFehler.setText(view.nachrichtGeloescht);
					view.lblFehler.setForeground(Color.GREEN);
					view.showInformation();
					return null;
				}
			};
			worker.execute();
		}
		if(src.equals(view.btnDateiAnhaengen)) {
			new AttachementHandler(view, "upload", null, -1);
		}
		if(src.equals(view.btnAbmelden)) {
			view.mailtool.logout();
			view.thisFrame.setVisible(false);
			view.loginFrame.pswrdfldPasswort.setText("");
			view.loginFrame.setVisible(true);
		}
		
	}

	@Override
	public void windowActivated(WindowEvent evt) { }

	@Override
	public void windowClosed(WindowEvent evt) { }

	@Override
	public void windowClosing(WindowEvent evt) {
		if(evt.getSource().equals(view.thisFrame)) {
			view.mailtool.logout();
			System.exit(0);
		}
	}

	@Override
	public void windowDeactivated(WindowEvent evt) { }

	@Override
	public void windowDeiconified(WindowEvent evt) { }

	@Override
	public void windowIconified(WindowEvent evt) { }

	@Override
	public void windowOpened(WindowEvent evt) { }

	@Override
	public void hyperlinkUpdate(HyperlinkEvent evt) {
		if(evt.getSource().equals(view.edtrpnEMailText2)) {
			HyperlinkEvent.EventType typ = evt.getEventType();
	        if (typ == HyperlinkEvent.EventType.ACTIVATED) {
	            try {
	                String urlFF = evt.getURL().toString();
	                urlFF = urlFF.replace("\\", "/");
	                urlFF = urlFF.replace(" ", "%20");
	                Desktop.getDesktop().browse(new URI(urlFF));
	            } catch (IOException ex) {
	                System.err.println("hyperlink not found!");
	            } catch (URISyntaxException ex) {
	                System.err.println("uri syntax exception!");
	            }
	        }
		}
	}
}